﻿CREATE FUNCTION QIC.Delegate_DEFAULT(@ConfigName VARCHAR(50))
RETURNS TABLE
AS
RETURN
(
	SELECT 
			Delegate.InterfaceId,
			Delegate.InterfaceName,
			Delegate.InterfaceType,
			Delegate.InterfaceSchemaName,
			Delegate.DelegateId,
			Delegate.DelegateName,
			Delegate.DelegateSchemaName,
			Delegate.TokenMap,
			Delegate.CallFactory
	FROM 
	(
		SELECT 
			Delegate.InterfaceId,
			Delegate.InterfaceName,
			Delegate.InterfaceType,
			Delegate.InterfaceSchemaName,
			Delegate.DelegateId,
			Delegate.DelegateName,
			Delegate.DelegateSchemaName,
			DelegateConfig.ThenTokenMap TokenMap,
			REPLACE(CAST(ISNULL(DelegateConfig.ThenCallFactory,Delegate.InterfaceType) as VARCHAR(50)),' ' ,'') CallFactory,
			ROW_NUMBER() OVER (PARTITION BY Delegate.InterfaceName,  Delegate.DelegateName Order by DelegateConfig.ThenPrio desc, Delegate.DelegateConfigName desc) Ranking
		FROM 
		(
			SELECT 
				Interface.InterfaceId InterfaceId,
				Interface.InterfaceName InterfaceName,
				Interface.InterfaceType,
				Interface.SchemaName InterfaceSchemaName,
				Delegate.object_id DelegateId,
				QIC.DelegateNameFactory_(Interface.InterfaceName,Delegate.name) DelegateName,
				QIC.DelegateConfigNameFactory_(Interface.InterfaceName,Delegate.name) DelegateConfigName,
				schemas.name DelegateSchemaName
			FROM QIC.Interface_(@ConfigName) Interface
			INNER JOIN sys.objects Delegate
				ON Interface.InterfaceType = Delegate.type
			INNER JOIN sys.schemas schemas
				ON schemas.schema_id = Delegate.schema_id
		) Delegate
		LEFT OUTER JOIN QIC.Config Config
			ON Config.Name = @ConfigName
		LEFT OUTER JOIN QIC.DelegateConfig DelegateConfig
			ON (DelegateConfig.WhenConfigName IS NULL OR DelegateConfig.WhenConfigName = Config.Name)
			AND (DelegateConfig.WhenSchemaName IS NULL OR DelegateConfig.WhenSchemaName = Delegate.DelegateSchemaName)
			AND (DelegateConfig.WhenDelegateName IS NULL OR DelegateConfig.WhenDelegateName = Delegate.DelegateName)
			AND (DelegateConfig.WhenInterfaceName IS NULL OR DelegateConfig.WhenInterfaceName = Delegate.InterfaceName)
			AND (DelegateConfig.WhenInterfaceType IS NULL OR DelegateConfig.WhenInterfaceType COLLATE DATABASE_DEFAULT = Delegate.InterfaceType COLLATE DATABASE_DEFAULT)
		WHERE Delegate.DelegateName is not null
		AND (Delegate.DelegateConfigName IS NULL OR Delegate.DelegateConfigName = @ConfigName)
		AND (ISNULL(DelegateConfig.ThenPrio,0) >= ISNULL(Config.MinPrio,0))
	) Delegate
	WHERE Delegate.Ranking = 1
);